In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Load pickled data
import pickle
import time
import random
import numpy as np
import csv
import tensorflow as tf
from tensorflow.python.client import device_lib
from tensorflow.contrib.layers import flatten
from sklearn.utils import shuffle
from sklearn import preprocessing
from skimage import exposure
import cv2
import pandas as pd
from matplotlib import gridspec
import matplotlib.pyplot as plt
%matplotlib inline
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos]
print("Available computing units: ", get_available_gpus())
training_file = "../train.p"
validation_file = "../valid.p"
testing_file = "../test.p"
labels_file = "signnames.csv"
colorspace = "BW" # ["RGB", "YUV", "LAB", "BW"]
show_signs = False
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
# check if we have equal amount of samples in the feature and label spaces
assert(len(X_train) == len(y_train))
assert(len(X_valid) == len(y_valid))
assert(len(X_test) == len(y_test))
# Read in label descriptions
labels = []
with open(labels_file, 'r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
if row[0].isdecimal():
labels.append(row[1])
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
n_train = X_train.shape[0]
n_validation = X_valid.shape[0]
n_test = X_test.shape[0]
image_shape = X_train.shape[1:]
n_classes = np.unique(y_train).size
n_total = n_train + n_validation + n_test
print("Training dataset size: %d (%.2f%%) samples" % (n_train, 100*n_train/n_total))
print("Validation dataset size: %d (%.2f%%) samples" % (n_validation, 100*n_validation/n_total))
print("Test dataset size: %d (%.2f%%) samples" % (n_test, 100*n_test/n_total))
print("Image data shape: ", image_shape)
print("Number of classes: ", n_classes)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
# Check how many traffic sign example we have in each class within the training dataset
class_indexes_train = []
class_indexes_valid = []
class_indexes_test = []
for i in range(n_classes):
class_indexes_train.append(np.where(y_train==i))
class_indexes_valid.append(np.where(y_valid==i))
class_indexes_test.append(np.where(y_test==i))
df = pd.DataFrame({
'Traffic sign description': labels,
'Training' : [len(class_indexes_train[i][0]) for i in range(n_classes)],
'Validation' : [len(class_indexes_valid[i][0]) for i in range(n_classes)],
'Test' : [len(class_indexes_test[i][0]) for i in range(n_classes)]
})
pd.options.display.width = 100
pd.options.display.max_colwidth = 90
df.reindex(columns=['Traffic sign description', 'Training', 'Validation', 'Test'])
def visualize_dataset(data, indexes, imgs_per_class=10):
#norm = colors.LogNorm(X_mean + 0.5 * X_std, 1.0, clip='True')
#norm = colors.LogNorm(vmin=-1.0, vmax=1.0)
#norm = colors.LogNorm(image.mean() + 0.5 * image.std(), image.max(), clip='True')
print("min val: %f, max val: %f" % (np.min(data), np.max(data)))
print("mean: %f, std: %f" %(data.mean(), data.std()))
data_conv = np.copy(data)
imshow_cmap = None
if data.shape[-1] == 1: # or colorspace == "BW"
imshow_cmap = "gray"
if colorspace == "YUV":
for i, img in enumerate(data):
data_conv[i] = np.reshape(cv2.cvtColor(img, cv2.COLOR_YUV2RGB), data.shape[1:])
elif colorspace == "LAB":
for i, img in enumerate(data):
data_conv[i] = np.reshape(cv2.cvtColor(img, cv2.COLOR_Lab2RGB), data.shape[1:])
for sign_class in range(n_classes):
print("Showing example images from class %d: %s" % (sign_class, labels[sign_class]))
plt.figure(figsize=(10,3))
rand_items = random.sample(list(indexes[sign_class][0]), imgs_per_class)
for count, i in zip(range(imgs_per_class), rand_items):
image = data_conv[i].squeeze()
ax = plt.subplot(1, imgs_per_class, count+1)
ax.set_title(i, fontdict={'fontsize': 8})
ax.set_axis_off()
ax.imshow(image, cmap=imshow_cmap) #, vmin=-1.0, vmax=1.0, cmap="gray", interpolation="lanczos")
plt.show(True)
if show_signs == True:
# visualize original dataset
visualize_dataset(X_train, class_indexes_train, imgs_per_class=10)
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
def equalize_dataset(data, colorspace_conversion=None):
adapthist_clipLimit = 0.05 # range: [0.0 - 1.0]
adapthist_grid_size = [8, 8] # kernel size in pixels
clahe_clipLimit = 5
clahe_grid_size = (5,5)
clahe = cv2.createCLAHE(clipLimit=clahe_clipLimit, tileGridSize=clahe_grid_size)
if colorspace == "BW":
data_norm = np.zeros((data.shape[0], data.shape[1], data.shape[2], 1))
else:
data_norm = np.copy(data)
if colorspace_conversion == "RGB":
print("no equalization for RGB images!")
# no equalization for RGB images, it only makes sense for brightness or luminosity channels!
elif colorspace_conversion == "YUV":
for i, img in enumerate(data):
data_norm[i] = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
y, u, v = cv2.split(data_norm[i])
#y = exposure.equalize_adapthist(y, clip_limit=adapthist_clipLimit, kernel_size=adapthist_grid_size)
y = clahe.apply(y)
data_norm[i] = np.reshape(cv2.merge((y,u,v)), data_norm.shape[1:])
elif colorspace_conversion == "LAB":
for i, img in enumerate(data):
data_norm[i] = cv2.cvtColor(img, cv2.COLOR_BGR2Lab)
l, a, b = cv2.split(data_norm[i])
#l = exposure.equalize_adapthist(l, clip_limit=adapthist_clipLimit, kernel_size=adapthist_grid_size)
l = clahe.apply(l)
data_norm[i] = np.reshape(cv2.merge((l,a,b)), data_norm.shape[1:])
elif colorspace_conversion=="BW":
for i, img in enumerate(data):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#img = exposure.equalize_adapthist(img, clip_limit=adapthist_clipLimit, kernel_size=adapthist_grid_size)
img = clahe.apply(img)
data_norm[i] = np.reshape(img, data_norm.shape[1:])
else:
print("No colorspace conversion set!")
#data_norm[i] = exposure.equalize_adapthist(data[i], clip_limit=adapthist_clipLimit, kernel_size=adapthist_grid_size)
return data_norm
def center_normalize(data, mean, std):
data = data.astype('float32')
#for i in range(data.shape[0]):
# data[i] = (data[i] - data[i].mean()) / (data[i].max() - data[i].min())
return (data - mean) / std
#return data
X_train_norm = equalize_dataset(X_train, colorspace)
X_valid_norm = equalize_dataset(X_valid, colorspace)
X_test_norm = equalize_dataset(X_test, colorspace)
X = np.concatenate((X_train, X_valid, X_test))
print("Total dataset mean: %d" % X.flatten().mean())
print("Total dataset std: %d" % X.flatten().std())
print("Before normalization: min val: %f, max val: %f" % (np.min(X_train_norm), np.max(X_train_norm)))
white_pixels_cnt = len(np.where(X_train == 255)[0])
black_pixels_cnt = len(np.where(X_train == 0)[0])
print("White & black pixels before equalization: %d, %d" % (white_pixels_cnt, black_pixels_cnt))
white_pixels_cnt = len(np.where(X_train_norm == 255)[0])
black_pixels_cnt = len(np.where(X_train_norm == 0)[0])
print("White & black pixels after equalization: %d, %d" % (white_pixels_cnt, black_pixels_cnt))
# Value normalization into -1 to +1 range
X_mean = 128
X_std = 128
X_train_norm = center_normalize(X_train_norm, X_mean, X_std)
X_valid_norm = center_normalize(X_valid_norm, X_mean, X_std)
X_test_norm = center_normalize(X_test_norm, X_mean, X_std)
print("Normalized data with mean=%.3f and scale=%.3f" % (X_mean, X_std))
print("After normalization min val: %f, max val: %f" % (np.min(X_train_norm), np.max(X_train_norm)))
datagen = ImageDataGenerator(
featurewise_center=False,
featurewise_std_normalization=False,
samplewise_center=False,
samplewise_std_normalization=False,
rotation_range=30,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=False,
vertical_flip=False,
zca_whitening=False,
zca_epsilon=1e-7,
shear_range=0.1,
zoom_range=0.1,
rescale=None
)
datagen.fit(X_train_norm, augment=True)
# Show 5 random images in original and equalized and normalized form
imshow_cmap="gray"
for i in random.sample(list(range(n_train)), 4):
plt.figure(figsize=(4,1))
ax = plt.subplot(1, 2, 1)
ax.set_axis_off()
ax.imshow(X_train[i].squeeze(), cmap=None)
ax = plt.subplot(1, 2, 2)
ax.set_axis_off()
print("min val: %f, max val: %f" % (np.min(X_train_norm[i]), np.max(X_train_norm[i])))
if colorspace == "YUV":
img = np.reshape(cv2.cvtColor(X_train_norm[i].squeeze(), cv2.COLOR_YUV2RGB), X_train_norm.shape[1:])
elif colorspace == "LAB":
img = np.reshape(cv2.cvtColor(X_train_norm[i].squeeze(), cv2.COLOR_Lab2RGB), X_train_norm.shape[1:])
else:
img = X_train_norm[i].squeeze()
ax.imshow(img, cmap=imshow_cmap)
plt.show()
# Test with different adaptive histogram equalization parameters
list_size = 10
for sample in [2900]: #random.sample(list(range(n_train)), 4):
X_norm =X_train[sample][:,:,0]
#X_norm = cv2.cvtColor(X_train[sample], cv2.COLOR_BGR2GRAY)
#X_norm = center_normalize(X_norm, X_mean, X_std)
plt.figure(figsize=(12,4))
imshow_cmap="gray"
#imshow_cmap=None
ax = plt.subplot(1, list_size, 1)
ax.set_title("orig", fontdict={'fontsize': 8})
ax.set_axis_off()
ax.imshow(X_norm, cmap=imshow_cmap) #, vmin=-1.0, vmax=1.0, cmap="gray", interpolation="lanczos")
for i in range(1, list_size):
clipLimit = i
grid_size = (4,4) #(i+2,i+2)
img = X_norm.astype("uint8")
clahe = cv2.createCLAHE(clipLimit=clipLimit, tileGridSize=grid_size)
img = np.reshape(clahe.apply(img), X_norm.shape)
#img = exposure.equalize_adapthist(img, clip_limit=clipLimit, kernel_size=grid_size)
#print("clipLimit: %f, grid_size: %s" % (clipLimit, grid_size))
ax = plt.subplot(1, list_size, i+1)
ax.set_title("clipLimit: %.2f\ngridSize: %s" %(clipLimit, grid_size), fontdict={'fontsize': 8})
ax.set_axis_off()
ax.imshow(img, cmap=imshow_cmap) #, vmin=-1.0, vmax=1.0, cmap="gray", interpolation="lanczos")
plt.tight_layout()
plt.show(True)
# show preprocessed images
if True: #show_signs == True:
X_train_batch, y_train_batch = datagen.flow(X_train_norm, y_train, batch_size=5000, shuffle=True).next()
indexes = []
for i in range(n_classes):
indexes.append(np.where(y_train_batch==i))
print("X_train_batch.shape: ", X_train_batch.shape)
visualize_dataset(X_train_batch, indexes, 10)
# first find class with least exmpales
import itertools
samples = []
for class_nr in range(n_classes):
samples.append(len(class_indexes_train[class_nr][0]))
class_min_size = np.argmin(np.array(samples))
class_max_size = np.argmax(np.array(samples))
min_size = len(class_indexes_train[class_min_size][0])
max_size = len(class_indexes_train[class_max_size][0])
print("min_size: %d, max_size: %d" % (min_size, max_size))
balanced_index = []
for class_nr in range(n_classes):
#balanced_index.append(random.sample(list(class_indexes_train[class_nr][0]), min_size))
size = len(class_indexes_train[class_nr][0])
int_multiple = max_size // size
rest = max_size % size
#print("Class %d: size=%d, int_multiple=%d, rest=%d" %(class_nr, size, int_multiple, rest))
for i in range(int_multiple):
balanced_index.append(class_indexes_train[class_nr][0])
balanced_index.append(random.sample(list(class_indexes_train[class_nr][0]), rest))
balanced_index = np.array(list(itertools.chain.from_iterable(balanced_index)))
print("final size: %d" % balanced_index.shape)
print("size should be %d" % (max_size * n_classes))
# Select model globally for training, validation and testing
model = "LeNet2"
# clean-up tensorflow before we build up the graph
tf.reset_default_graph()
# Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
mu = 0
sigma = 0.1
# really make sure it gets the dimensions right!
if colorspace == "BW":
image_shape = (image_shape[0], image_shape[1], 1)
def maxpool2d(x, k=2, s=2, padding='VALID'):
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, s, s, 1], padding=padding)
def conv2d(x, W, b, strides=1, padding='VALID'):
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding=padding)
x = tf.nn.bias_add(x, b)
return tf.nn.elu(x)
#new_height = (input_height - filter_height + 2 * P)/S + 1
# Layers weights & biases for LeNet1
weights1 = {
'wc1': tf.Variable(tf.random_normal([5, 5, image_shape[2], 6], mean=mu, stddev=sigma)),
'wc2': tf.Variable(tf.random_normal([5, 5, 6, 16], mean=mu, stddev=sigma)),
'wfull1': tf.Variable(tf.random_normal([400, 120], mean=mu, stddev=sigma)),
'wfull2': tf.Variable(tf.random_normal([120, 84], mean=mu, stddev=sigma)),
'out': tf.Variable(tf.random_normal([84, n_classes], mean=mu, stddev=sigma))
}
biases1 = {
'bc1': tf.Variable(tf.random_normal([6], mean=mu, stddev=sigma)),
'bc2': tf.Variable(tf.random_normal([16], mean=mu, stddev=sigma)),
'bfull1': tf.Variable(tf.random_normal([120], mean=mu, stddev=sigma)),
'bfull2': tf.Variable(tf.random_normal([84], mean=mu, stddev=sigma)),
'out': tf.Variable(tf.random_normal([n_classes], mean=mu, stddev=sigma))
}
def LeNet1(x, keep_prob):
# Layer 1: Convolutional. Input = 32x32ximage_shape[2]. Output = 28x28x6.
conv1 = conv2d(x, weights1['wc1'], biases1['bc1'], strides=1, padding='VALID')
# Pooling. Input = 28x28x6. Output = 14x14x6.
conv1 = maxpool2d(conv1, k=2, s=2)
# Layer 2: Convolutional. Output = 10x10x16.
conv2 = conv2d(conv1, weights1['wc2'], biases1['bc2'], padding='VALID')
# Pooling. Input = 10x10x16. Output = 5x5x16.
conv2 = maxpool2d(conv2, k=2, s=2)
# Flatten. Input = 5x5x16. Output = 400.
flat = flatten(conv2)
# Layer 3: Fully Connected. Input = 400. Output = 120.
layer3 = tf.add(tf.matmul(flat, weights1['wfull1']), biases1['bfull1'])
# Activation.
layer3 = tf.nn.elu(layer3)
# Dropout
layer3 = tf.nn.dropout(layer3, keep_prob)
# Layer 4: Fully Connected. Input = 120. Output = 84.
layer4 = tf.add(tf.matmul(layer3, weights1['wfull2']), biases1['bfull2'])
# Activation.
layer4 = tf.nn.elu(layer4)
# Dropout
layer4 = tf.nn.dropout(layer4, keep_prob)
# Layer 5: Fully Connected. Input = 84. Output = n_classes.
logits = tf.add(tf.matmul(layer4, weights1['out']), biases1['out'])
net = {"conv1": conv1, "conv2": conv2, "layer3": layer3, "layer4": layer4, "logits": logits}
return net
# Layers weights & biases for LeNet2
weights2 = {
'wc1': tf.Variable(tf.random_normal([5, 5, image_shape[2], 32], mean=mu, stddev=sigma)),
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64], mean=mu, stddev=sigma)),
'wc3': tf.Variable(tf.random_normal([5, 5, 64, 128], mean=mu, stddev=sigma)),
'wfull1': tf.Variable(tf.random_normal([2048, 400], mean=mu, stddev=sigma)),
'wfull2': tf.Variable(tf.random_normal([400, 200], mean=mu, stddev=sigma)),
'out': tf.Variable(tf.random_normal([200, n_classes], mean=mu, stddev=sigma))
}
biases2 = {
'bc1': tf.Variable(tf.random_normal([32], mean=mu, stddev=sigma)),
'bc2': tf.Variable(tf.random_normal([64], mean=mu, stddev=sigma)),
'bc3': tf.Variable(tf.random_normal([128], mean=mu, stddev=sigma)),
'bfull1': tf.Variable(tf.random_normal([400], mean=mu, stddev=sigma)),
'bfull2': tf.Variable(tf.random_normal([200], mean=mu, stddev=sigma)),
'out': tf.Variable(tf.random_normal([n_classes], mean=mu, stddev=sigma))
}
def LeNet2(x, keep_prob):
# Layer 1: Convolutional. Input = 32x32ximage_shape[2]. Output = 32x32x32.
conv1 = conv2d(x, weights2['wc1'], biases2['bc1'], strides=1, padding='SAME')
# Pooling. Input = 32x32x32. Output = 16x16x32.
conv1 = maxpool2d(conv1, k=2, s=2, padding='SAME')
# Layer 2: Convolutional. Output = 16x16x64.
conv2 = conv2d(conv1, weights2['wc2'], biases2['bc2'], padding='SAME')
# Pooling. Input = 16x16x64. Output = 8x8x64.
conv2 = maxpool2d(conv2, k=2, s=2, padding='SAME')
# Layer 3: Convolutional. Output = 8x8x128.
conv3 = conv2d(conv2, weights2['wc3'], biases2['bc3'], padding='SAME')
# Pooling. Input = 8x8x128. Output = 4x4x128.
conv3 = maxpool2d(conv3, k=2, s=2, padding='SAME')
# Flatten. Input = 4x4x128. Output = 400.
flat = flatten(conv3)
# Layer 4: Fully Connected. Input = 2048. Output = 400.
layer4 = tf.add(tf.matmul(flat, weights2['wfull1']), biases2['bfull1'])
# Activation.
layer4 = tf.nn.elu(layer4)
# Dropout
layer4 = tf.nn.dropout(layer4, keep_prob)
# Layer 5: Fully Connected. Input = 400. Output = 200.
layer5 = tf.add(tf.matmul(layer4, weights2['wfull2']), biases2['bfull2'])
# Activation.
layer5 = tf.nn.elu(layer5)
# Dropout
layer5 = tf.nn.dropout(layer5, keep_prob)
# Layer 6: Fully Connected. Input = 200. Output = n_classes.
logits = tf.add(tf.matmul(layer5, weights2['out']), biases2['out'])
net = {"conv1": conv1, "conv2": conv2, "conv3": conv3, "layer4": layer4, "layer5": layer5, "logits": logits}
return net
# Variables and placeholders
x = tf.placeholder(tf.float32, (None, 32, 32, image_shape[2]))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
# Creating instance of one of the networks
if model == "LeNet1":
net = LeNet1(x, keep_prob)
logits = net["logits"]
BATCH_SIZE = 8192
save_filename = "./lenet1"
else:
net = LeNet2(x, keep_prob)
logits = net["logits"]
BATCH_SIZE = 2048
save_filename = "./lenet2"
save_filename += "-" + colorspace
# Tensor definitions
one_hot_y = tf.one_hot(y, n_classes)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer() # ,learning_rate=learning_rate)
training_operation = optimizer.minimize(loss_operation)
# Calculate and report the accuracy on the training and validation set
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver(filename=save_filename)
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_examples
# training the model
rate_start = 0.001
dropout = 0.2 # Dropout, probability to keep units
epochs = 5
biased_index = []
biased_index.append(class_indexes_train[30][0])
biased_index.append(class_indexes_train[27][0])
biased_index = np.array(list(itertools.chain.from_iterable(biased_index)))
sample_selection = balanced_index #range(n_train) #balanced_index #biased_index
print("Model parameters: %d" % np.sum([np.prod(v.shape) for v in tf.trainable_variables()]))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
if tf.train.latest_checkpoint('.'):
print("Trying to load model and variables from last checkpoint: %s" % tf.train.latest_checkpoint('.'))
saver.restore(sess, tf.train.latest_checkpoint('.'))
#saver.restore(sess, save_filename)
else:
print("Not checkpoint found, starting training from scratch!")
print("Training...")
for step in range(epochs):
t0 = time.time()
#batch_cnt = n_train//BATCH_SIZE + 1
batch_cnt = len(sample_selection)//BATCH_SIZE + 1
batches = 0
for X_train_batch, y_train_batch in datagen.flow(X_train_norm[sample_selection], y_train[sample_selection], batch_size=BATCH_SIZE, shuffle=True):
sess.run(training_operation, feed_dict={x: X_train_batch, y: y_train_batch, keep_prob: dropout})
batches += 1
if batches > batch_cnt:
break
loss = sess.run(loss_operation, feed_dict={x: X_train_batch, y: y_train_batch, keep_prob: 1.0})
validation_accuracy = evaluate(X_valid_norm, y_valid)
print("Epoch %d took %.2fs - Loss: %.5f, Validation Accuracy: %.5f" %
(step + 1, time.time() - t0, loss, validation_accuracy))
saver.save(sess, save_filename, global_step=step)
saver.save(sess, save_filename)
print("Model saved")
Setting up a slightly different model with more parameters in keras to learn how the abstraction layer of tensorflow work. Wow, this really is much easier and convenient to set-up...
keras.backend.clear_session()
keras_savename="LeNet3.weights"
if colorspace == "BW":
image_shape = (image_shape[0], image_shape[1], 1)
def LeNet3_model(keep_prob=0.5):
# really make sure it gets the dimensions right!
model = Sequential()
model.add(Conv2D(64, kernel_size=(3, 3), input_shape=image_shape, activation='elu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(128, (3, 3), activation='elu'))
model.add(MaxPooling2D((2, 2)))
model.add((Dropout(keep_prob)))
model.add(Flatten())
model.add(Dense(256, activation='elu'))
model.add(Dropout(keep_prob))
model.add(Dense(43, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])
return model
LeNet3 = LeNet3_model(0.2)
try:
LeNet3.load_weights(keras_savename)
except:
print("Could not load weights for LeNet3 keras model, starting training from scratch!")
# convert class vectors to binary class matrices
y_train_keras = keras.utils.to_categorical(y_train, n_classes)
y_valid_keras = keras.utils.to_categorical(y_valid, n_classes)
y_test_keras = keras.utils.to_categorical(y_test, n_classes)
Training model
epochs = 5
biased_index = []
biased_index.append(class_indexes_train[30][0])
biased_index.append(class_indexes_train[27][0])
biased_index = np.array(list(itertools.chain.from_iterable(biased_index)))
sample_selection = balanced_index #range(n_train) #balanced_index #biased_index
BATCH_SIZE = 4096
LeNet3.summary()
LeNet3.fit_generator(datagen.flow(X_train_norm[sample_selection], y_train_keras[sample_selection], batch_size=BATCH_SIZE),
steps_per_epoch=len(sample_selection) // BATCH_SIZE, epochs=epochs,
validation_data=(X_valid_norm, y_valid_keras), verbose=1)
score = LeNet3.evaluate(X_test_norm, y_test_keras, verbose=1)
print("Test loss: ", score[0])
print("Test accuracy:", score[1])
LeNet3.save_weights(keras_savename)
# Test on whole test dataset and for each class
accuracies = []
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
train_accuracy = evaluate(X_train_norm, y_train)
valid_accuracy = evaluate(X_valid_norm, y_valid)
test_accuracy = evaluate(X_test_norm, y_test)
print("Training Accuracy = %.3f" % train_accuracy)
print("Validation Accuracy = %.3f" % valid_accuracy)
print("Test Accuracy = %.3f" % test_accuracy)
for i, sign in enumerate(class_indexes_test):
accuracies.append(evaluate(X_test_norm[sign[0]], y_test[sign[0]]))
fig = plt.figure(figsize=(11,3))
ax = plt.bar(range(n_classes), accuracies, align="center", width=0.8)
plt.xticks(range(n_classes), range(n_classes))
plt.xlabel("Traffic sign classes")
plt.ylabel("Accuracy on test dataset")
plt.axis("tight")
#fig.savefig("./examples/pred_tf_test1.png", bbox_inches="tight")
plt.show(True)
# Keras test network accuracy
train_accuracy = LeNet3.evaluate(X_train_norm, keras.utils.to_categorical(y_train, n_classes), verbose=0)[1]
valid_accuracy = LeNet3.evaluate(X_valid_norm, keras.utils.to_categorical(y_valid, n_classes), verbose=0)[1]
test_accuracy = LeNet3.evaluate(X_test_norm, keras.utils.to_categorical(y_test, n_classes), verbose=0)[1]
print("Training Accuracy = %.3f" % train_accuracy)
print("Validation Accuracy = %.3f" % valid_accuracy)
print("Test Accuracy = %.3f" % test_accuracy)
accuracies = []
for i, sign in enumerate(class_indexes_test):
pred = LeNet3.evaluate(X_test_norm[sign[0]], keras.utils.to_categorical(y_test[sign[0]], n_classes), verbose=0)[1]
accuracies.append(pred)
fig = plt.figure(figsize=(11,3))
plt.bar(range(n_classes), accuracies, align="center", width=0.8)
plt.xticks(range(n_classes), range(n_classes))
plt.xlabel("Traffic sign classes")
plt.ylabel("Accuracy on test dataset")
plt.axis("tight")
#fig.savefig("./examples/pred_tf_test2.png", bbox_inches="tight")
plt.show(True)
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
import os
import matplotlib.image as mpimg
import scipy
test_images = []
test_labels = [22, 27, 14, 25, 25, 12, 23, 27]
img_src_folder = "extra-examples/"
imagefile_list = sorted(os.listdir(img_src_folder))
for count, imagefile in enumerate(imagefile_list):
image = mpimg.imread(img_src_folder + imagefile)
img = scipy.misc.imresize(image, (32, 32), interp="lanczos")
ax = plt.subplot(1, len(imagefile_list), count+1)
ax.set_title(imagefile, fontdict={'fontsize': 8})
ax.set_axis_off()
ax.imshow(img)
test_images.append(img)
plt.show(True)
# equalize and normalize data
test_images_norm = equalize_dataset(np.array(test_images), colorspace)
test_images_norm = center_normalize(test_images_norm, X_mean, X_std)
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
nr_top = 5
top = tf.nn.top_k(tf.nn.softmax(logits), k=nr_top)
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
for i in range(len(test_images_norm)):
feed = {x: np.expand_dims(test_images_norm[i], axis=0), keep_prob: 1}
values, indicies = sess.run(top, feed_dict=feed)
fig1 = plt.figure(figsize=(4,3))
gs = gridspec.GridSpec(4,3)
ax = plt.subplot2grid((4,3), (0,2))
ax.imshow(test_images[i].squeeze())
ax.set_axis_off()
ax = plt.subplot2grid((4,3), (1,2))
ax.imshow(test_images_norm[i].squeeze(), cmap="gray")
ax.set_axis_off()
plt.subplot2grid((4,3), (0,0), colspan=2, rowspan=2)
plt.title("%s detection of '%s' sign (class %d)!" %
("Correct" if indicies.flatten()[0] == test_labels[i] else "Wrong",
labels[test_labels[i]], test_labels[i]), loc="right")
plt.barh(range(5), values.flatten(), align="center")
plt.yticks(range(5), ['{:>45}'.format(labels[i]) for i in indicies.flatten()])
plt.xlabel("Prediction probability")
plt.xlim(0, 1)
#fig1.savefig("./examples/pred_tf%d.png" % i, bbox_inches="tight")
plt.show(True)
### Calculate the accuracy for these new images.
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
test_accuracy = evaluate(test_images_norm, test_labels)
print("Test image accuracy = %.3f" % test_accuracy)
Because of the higher amount of features captured by the keras test model I expect a slightly higher accuracy.
nr_top = 5
top = tf.nn.top_k(LeNet3.predict(test_images_norm), k=nr_top)
with tf.Session() as sess:
tops = sess.run(top)
for i in range(len(test_images_norm)):
values, indicies = tops[0][i], tops[1][i]
fig1 = plt.figure(figsize=(4,3))
gs = gridspec.GridSpec(4,3)
ax = plt.subplot2grid((4,3), (0,2))
ax.imshow(test_images[i].squeeze())
ax.set_axis_off()
ax = plt.subplot2grid((4,3), (1,2))
ax.imshow(test_images_norm[i].squeeze(), cmap="gray")
ax.set_axis_off()
plt.subplot2grid((4,3), (0,0), colspan=2, rowspan=2)
plt.title("%s detection of '%s' sign (class %d)!" %
("Correct" if indicies.flatten()[0] == test_labels[i] else "Wrong",
labels[test_labels[i]], test_labels[i]), loc="right")
plt.barh(range(5), values.flatten(), align="center")
plt.yticks(range(5), ['{:>45}'.format(labels[i]) for i in indicies.flatten()])
plt.xlabel("Prediction probability")
plt.xlim(0, 1)
plt.show(True)
# Keras test network accuracy
test_accuracy = LeNet3.evaluate(test_images_norm, keras.utils.to_categorical(test_labels, n_classes), verbose=0)[1]
print("Test Accuracy = %.3f" % test_accuracy)
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
Your output should look something like this (above)
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activations, activation_name=None, activation_min=-1, activation_max=1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# equalize and normalize data
#image_input = equalize_dataset(image_input, colorspace)
#image_input = center_normalize(image_input, X_mean, X_std)
if activation_name not in tf_activations:
print("Activation layer not found in given tf_activation list!")
return -1
activation = tf_activations[activation_name].eval(session=sess, feed_dict={x: image_input})
featuremaps = activation.shape[3]
plt.figure(plt_num, figsize=(12,10))
#plt.suptitle("Featuremaps (size: %d)" % featuremaps, fontsize=12)
print("Layer %s featuremaps (size: %d)" % (activation_name, featuremaps))
for featuremap in range(featuremaps):
ax = plt.subplot(featuremaps//8, 8, featuremap+1) # sets the number of feature maps to show on each row and column
#plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
ax.set_title('FeatureMap ' + str(featuremap), fontdict={'fontsize': 8})
ax.set_axis_off()
if activation_min != -1 and activation_max != -1:
ax.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
ax.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
ax.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
ax.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
plt.tight_layout(h_pad=0.01, w_pad=0.01, pad=0.1)
plt.show()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
net = LeNet2(x, keep_prob)
print("conv1:")
outputFeatureMap(X_train_norm[class_indexes_train[20][0]], net, "conv1")
#outputFeatureMap(X_train_norm, net, "conv1")
print("conv2:")
outputFeatureMap(X_train_norm[class_indexes_train[20][0]], net, "conv2")
#outputFeatureMap(X_train_norm, net, "conv2")